package com.csun.cmny.provider.service.impl;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.provider.dao.DmcLifeTransducerRoomConfigMapper;
import com.csun.cmny.provider.device.csun.camera.CameraMessageHandler;
import com.csun.cmny.provider.device.csun.gateway.GatewayMessageSender;
import com.csun.cmny.provider.model.constant.LifeConstant;
import com.csun.cmny.provider.model.domain.*;
import com.csun.cmny.provider.model.dto.life.LifeTransducerConfigDto;
import com.csun.cmny.provider.model.vo.RoomBuildingVo;
import com.csun.cmny.provider.model.vo.life.LifeTransducerConfigVO;
import com.csun.cmny.provider.service.*;
import com.xiaoleilu.hutool.convert.Convert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@Transactional
public class DmcLifeTransducerRoomConfigServiceImpl extends BaseService<DmcLifeTransducerRoomConfig> implements DmcLifeTransducerRoomConfigService {
    @Resource
    private DmcLifeTransducerRoomConfigMapper dmcLifeTransducerRoomConfigMapper;
    @Resource
    private DmcLifeTransducerDefaultConfigService dmcLifeTransducerDefaultConfigService;
    @Resource
    private DmcCsunBodySensorConfigService dmcCsunBodySensorConfigService;
    @Resource
    private DmcCsunHumidistatLocationService dmcCsunHumidistatLocationService;
    @Resource
    private DmcCsunHumidistatConfigService dmcCsunHumidistatConfigService;
    @Resource
    private DmcCsunHumidistatThresholdService dmcCsunHumidistatThresholdService;
    @Resource
    private DmcCsunSleepBindService dmcCsunSleepBindService;
    @Resource
    private DmcCsunSleepConfigService dmcCsunSleepConfigService;
    @Resource
    private DmcCsunSleepThresholdService dmcCsunSleepThresholdService;
    @Resource
    private DmcCsunCameraConfigService dmcCsunCameraConfigService;
    @Resource
    private DmcCsunCameraLocationService dmcCsunCameraLocationService;
    @Resource
    private GatewayMessageSender gatewayMessageSender;
    @Resource
    private DmcCsunBodySensorLocationService dmcCsunwBodyLocationService;
    @Resource
    private CameraMessageHandler cameraMessageHandler;
    @Resource
    private OmcRpcService omcRpcService;

    @Override
    public Integer updateById(LifeTransducerConfigDto dto, LoginAuthDto loginAuthDto) {

        //查询该房间配置
        DmcLifeTransducerRoomConfig originalConfig = selectByKey(dto.getRoomId());
        DmcLifeTransducerRoomConfig roomConfig = new DmcLifeTransducerRoomConfig();

        //拷贝属性
        BeanUtils.copyProperties(dto,roomConfig);

        //人感设置
        setNewBodySensorConfig(roomConfig,loginAuthDto);
        //温度计设置
        setCsunHumidistatConfigAndThreshold(roomConfig,loginAuthDto);
        //床垫设置
        setCsunSleepConfigAndThreshold(roomConfig,loginAuthDto);
        //摄像头设置
        setCsunCameraConfig(roomConfig,loginAuthDto);

        //存在则修改，不存在时新增
        if (originalConfig == null) {
            if(roomConfig.getGroupId() == null || roomConfig.getGroupId().equals(0)){
                roomConfig.setGroupId(loginAuthDto.getGroupId());
            }
            //将配置同步到【设备阈值表】和【设备设置表】中
            return dmcLifeTransducerRoomConfigMapper.insertSelective(roomConfig);
        }else{
            return dmcLifeTransducerRoomConfigMapper.updateByPrimaryKeySelective(roomConfig);
        }
    }

    @Override
    public LifeTransducerConfigVO getConfigByRoomId(Long roomId, LoginAuthDto loginAuthDto) {
        LifeTransducerConfigVO vo = new LifeTransducerConfigVO();
        DmcLifeTransducerRoomConfig dmcLifeTransducerConfig =  dmcLifeTransducerRoomConfigMapper.selectByPrimaryKey(roomId);
        if(dmcLifeTransducerConfig == null){
            LifeTransducerConfigVO defaultConfig = dmcLifeTransducerDefaultConfigService.getDefaultConfigByGroupId(loginAuthDto.getGroupId());
            BeanUtils.copyProperties(defaultConfig,vo);
        }else {
            BeanUtils.copyProperties(dmcLifeTransducerConfig,vo);
        }
        return vo;
    }

    public void setNewBodySensorConfig(DmcLifeTransducerRoomConfig roomConfig,LoginAuthDto loginAuthDto) {
        DmcCsunBodySensorLocation bodySensorLocation = new DmcCsunBodySensorLocation();
        bodySensorLocation.setRoomId(roomConfig.getRoomId().intValue());
        List<DmcCsunBodySensorLocation> bodySensorLocations = dmcCsunwBodyLocationService.select(bodySensorLocation);
        if(bodySensorLocations.size() > 0){
            for (DmcCsunBodySensorLocation d : bodySensorLocations) {
                Long deviceId = d.getDeviceId();

                DmcCsunBodySensorConfig csunBodySensorConfig = dmcCsunBodySensorConfigService.selectByKey(deviceId);
                DmcCsunBodySensorConfig config = new DmcCsunBodySensorConfig();
                //放入数据
                config.setToiletAttentionTime(roomConfig.getToiletAttentionTime());
                config.setIsUseToiletAttentionTime(roomConfig.getIsUseToiletAttentionTime());
                config.setToiletUnusualTime(roomConfig.getToiletUnusualTime());
                config.setIsUseToiletWarningTime(roomConfig.getIsUseToiletWarningTime());
                config.setToiletWarningTime(roomConfig.getToiletWarningTime());
                config.setIsUseToiletUnusualTime(roomConfig.getIsUseToiletUnusualTime());
                config.setIsSend(LifeConstant.DEVICE_ORDER_NEED_SEND);
                config.setLastOperator(loginAuthDto.getUserName());
                config.setLastOperatorId(loginAuthDto.getUserId());
                config.setDeviceId(deviceId);

                gatewayMessageSender.setLifeBodySensorTimer(deviceId.toString(),roomConfig.getToiletAttentionTime().toString(),roomConfig.getToiletWarningTime().toString(),roomConfig.getToiletUnusualTime().toString());

                //没有则新增、有则修改
                if(csunBodySensorConfig == null){
                    config.setCreator(loginAuthDto.getUserName());
                    config.setCreatorId(loginAuthDto.getUserId());
                    dmcCsunBodySensorConfigService.save(config);
                }else{
                    config.setUpdateTime(new Date());
                    dmcCsunBodySensorConfigService.update(config);
                }
            }
        }
    }

    public void setCsunHumidistatConfigAndThreshold(DmcLifeTransducerRoomConfig roomConfig, LoginAuthDto loginAuthDto){
        //温度计
        DmcCsunHumidistatLocation csunHumidistatLocation = new DmcCsunHumidistatLocation();
        csunHumidistatLocation.setRoomId(roomConfig.getRoomId().intValue());
        List<DmcCsunHumidistatLocation> csunHumidistatLocationList = dmcCsunHumidistatLocationService.select(csunHumidistatLocation);
        if(csunHumidistatLocationList.size() > 0){
            for (DmcCsunHumidistatLocation d : csunHumidistatLocationList) {
                Long deviceId = d.getDeviceId();

                //1.下发时间指令
                DmcCsunHumidistatConfig csunHumidistatConfig = dmcCsunHumidistatConfigService.selectByKey(deviceId);
                DmcCsunHumidistatConfig config = new DmcCsunHumidistatConfig();

                config.setDeviceId(deviceId);
                config.setTemperatureMeasuringTimeInterval(roomConfig.getTemperatureMeasuringTimeInterval());
                config.setIsSend(LifeConstant.DEVICE_ORDER_NEED_SEND);
                config.setLastOperator(loginAuthDto.getUserName());
                config.setLastOperatorId(loginAuthDto.getUserId());

                if(csunHumidistatConfig == null){
                    config.setCreator(loginAuthDto.getUserName());
                    config.setCreatorId(loginAuthDto.getUserId());
                    dmcCsunHumidistatConfigService.save(config);
                }else{
                    dmcCsunHumidistatConfigService.update(config);
                }

                /**
                 * @date    2020-01-07
                 * @author  chisj
                 * @desc    下发温湿度配置
                 */
                gatewayMessageSender.setHumidistatTimer(deviceId, roomConfig.getTemperatureMeasuringTimeInterval());

                //2.设置阈值
                DmcCsunHumidistatThreshold csunHumidistatThreshold = dmcCsunHumidistatThresholdService.selectByKey(deviceId);
                DmcCsunHumidistatThreshold threshold = new DmcCsunHumidistatThreshold();

                threshold.setTemperatureMaximum(roomConfig.getTemperatureMaximum());
                threshold.setTemperatureMinimum(roomConfig.getTemperatureMinimum());
                threshold.setDeviceId(deviceId);
                threshold.setLastOperator(loginAuthDto.getUserName());
                threshold.setLastOperatorId(loginAuthDto.getUserId());

                if(csunHumidistatThreshold == null){
                    threshold.setCreator(loginAuthDto.getUserName());
                    threshold.setCreatorId(loginAuthDto.getUserId());
                    dmcCsunHumidistatThresholdService.save(threshold);
                }else{
                    dmcCsunHumidistatThresholdService.update(threshold);
                }
            }
        }
    }

    public void setCsunSleepConfigAndThreshold(DmcLifeTransducerRoomConfig roomConfig, LoginAuthDto loginAuthDto){

        //床垫
        DmcCsunSleepBind bind = new DmcCsunSleepBind();
        bind.setRoomId(roomConfig.getRoomId().intValue());
        List<DmcCsunSleepBind> csunRoomBindSleepBindList = dmcCsunSleepBindService.select(bind);
        List<Integer> bedIdList = omcRpcService.listBedByRoomId(roomConfig.getRoomId().intValue());
        if(bedIdList.size() > 0){
            bedIdList.forEach(b -> {
                DmcCsunSleepBind bindQuery = new DmcCsunSleepBind();
                bindQuery.setBedId(b);
                List<DmcCsunSleepBind> dmcCsunSleepBinds = dmcCsunSleepBindService.select(bindQuery);
                if(dmcCsunSleepBinds.size() > 0){
                    csunRoomBindSleepBindList.addAll(dmcCsunSleepBinds);
                }
            });
        }

        if(csunRoomBindSleepBindList.size() > 0){
            for (DmcCsunSleepBind d : csunRoomBindSleepBindList) {
                Long deviceId = d.getDeviceId();

                //1.下发时间指令
                DmcCsunSleepConfig csunHumidistatConfig = dmcCsunSleepConfigService.selectByKey(deviceId);
                DmcCsunSleepConfig config = new DmcCsunSleepConfig();

                config.setDeviceId(deviceId);
                config.setVitalMeasuringTimeInterval(roomConfig.getVitalMeasuringTimeInterval());
                config.setIsSend(LifeConstant.DEVICE_ORDER_NEED_SEND);
                config.setLastOperator(loginAuthDto.getUserName());
                config.setLastOperatorId(loginAuthDto.getUserId());

                if(csunHumidistatConfig == null){
                    config.setCreator(loginAuthDto.getUserName());
                    config.setCreatorId(loginAuthDto.getUserId());
                    dmcCsunSleepConfigService.save(config);
                }else{
                    dmcCsunSleepConfigService.update(config);
                }

                //2.设置阈值
                DmcCsunSleepThreshold dmcCsunSleepThreshold = dmcCsunSleepThresholdService.selectByKey(deviceId);
                DmcCsunSleepThreshold threshold = new DmcCsunSleepThreshold();

                threshold.setDeviceId(deviceId);
                threshold.setLeaveBedMeasuringTimeInterval(roomConfig.getLeaveBedMeasuringTimeInterval());
                threshold.setMaxBreathThreshold(roomConfig.getBreathMaxTimes());
                threshold.setMinBreathThreshold(roomConfig.getBreathMinTimes());
                threshold.setMaxHeartbeatThreshold(roomConfig.getHeartbeatMaximum());
                threshold.setMinHeartbeatThreshold(roomConfig.getHeartbeatMinimum());
                threshold.setLastOperator(loginAuthDto.getUserName());
                threshold.setLastOperatorId(loginAuthDto.getUserId());

                if(dmcCsunSleepThreshold == null){
                    threshold.setCreator(loginAuthDto.getUserName());
                    threshold.setCreatorId(loginAuthDto.getUserId());
                    dmcCsunSleepThresholdService.save(threshold);
                }else{
                    dmcCsunSleepThresholdService.update(threshold);
                }
            }
        }
    }

    public void setCsunCameraConfig(DmcLifeTransducerRoomConfig roomConfig, LoginAuthDto loginAuthDto) {
        DmcCsunCameraLocation csunCameraLocation = new DmcCsunCameraLocation();
        csunCameraLocation.setRoomId(roomConfig.getRoomId().intValue());
        List<DmcCsunCameraLocation> csunCameraLocations = dmcCsunCameraLocationService.select(csunCameraLocation);
        if(csunCameraLocations.size() > 0){
            for (DmcCsunCameraLocation d : csunCameraLocations) {
                Long deviceId = d.getDeviceId();

                //1.下发时间指令
                DmcCsunCameraConfig dmcCsunCameraConfig = dmcCsunCameraConfigService.selectByKey(deviceId);
                DmcCsunCameraConfig config = new DmcCsunCameraConfig();

                config.setDeviceId(deviceId);
                config.setTumbleMeasuringFrame(roomConfig.getTumbleMeasuringFrame());
                config.setWalkMeasuringEndTime(roomConfig.getWalkMeasuringEndTime());
                config.setWalkMeasuringStartTime(roomConfig.getWalkMeasuringStartTime());
                config.setWalkMeasuringTimeInterval(roomConfig.getWalkMeasuringTimeInterval());
                config.setCameraCheckTime(roomConfig.getCameraCheckTime());
                config.setBeforeDuration(roomConfig.getBeforeDuration());
                config.setAfterDuration(roomConfig.getAfterDuration());
                config.setIsSend(LifeConstant.DEVICE_ORDER_NEED_SEND);
                config.setLastOperator(loginAuthDto.getUserName());
                config.setLastOperatorId(loginAuthDto.getUserId());

                if(dmcCsunCameraConfig == null){
                    config.setCreator(loginAuthDto.getUserName());
                    config.setCreatorId(loginAuthDto.getUserId());
                    dmcCsunCameraConfigService.save(config);
                }else{
                    dmcCsunCameraConfigService.update(config);
                }

                /**
                 * @date    2020-01-09
                 * @author  chisj
                 * @desc    下发摄像头配置
                 */
                cameraMessageHandler.sendCameraConfigMsg(deviceId,
                        roomConfig.getWalkMeasuringStartTime(),
                        roomConfig.getWalkMeasuringEndTime(),
                        roomConfig.getWalkMeasuringTimeInterval(),
                        roomConfig.getTumbleMeasuringFrame(),
                        roomConfig.getCameraCheckTime(),
                        roomConfig.getBeforeDuration(),
                        roomConfig.getAfterDuration());
            }
        }
    }

}
